package com.example.controller;

import com.example.entity.Document;
import com.example.service.DocumentService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.List;
import java.util.Optional;

/**
 * 文档控制器
 * 提供REST API接口
 */
@Slf4j
@RestController
@RequestMapping("/api/documents")
@RequiredArgsConstructor
public class DocumentController {

    private final DocumentService documentService;

    /**
     * 初始化索引和测试数据
     */
    @PostMapping("/init")
    public ResponseEntity<String> init() {
        documentService.initIndex();
        
        // 创建测试数据
        List<Document> testDocuments = Arrays.asList(
            new Document("SpringBoot入门教程", "本教程详细介绍SpringBoot框架的使用方法", "张三", 
                Arrays.asList("SpringBoot", "Java", "教程")),
            new Document("Elasticsearch实战", "深入浅出Elasticsearch搜索引擎技术", "李四", 
                Arrays.asList("Elasticsearch", "搜索引擎", "大数据")),
            new Document("微服务架构设计", "介绍微服务架构的设计原则和最佳实践", "王五", 
                Arrays.asList("微服务", "架构", "分布式")),
            new Document("Docker容器化部署", "使用Docker进行应用容器化部署的完整指南", "张三", 
                Arrays.asList("Docker", "容器", "DevOps")),
            new Document("Redis缓存优化", "Redis在高并发场景下的缓存优化策略", "赵六", 
                Arrays.asList("Redis", "缓存", "性能优化"))
        );
        
        documentService.saveAll(testDocuments);
        return ResponseEntity.ok("初始化完成，已创建测试数据");
    }

    /**
     * 创建文档
     */
    @PostMapping
    public ResponseEntity<Document> createDocument(@RequestBody Document document) {
        document.setCreateTime(LocalDateTime.now());
        Document saved = documentService.save(document);
        return ResponseEntity.ok(saved);
    }

    /**
     * 批量创建文档
     */
    @PostMapping("/batch")
    public ResponseEntity<String> createDocuments(@RequestBody List<Document> documents) {
        documents.forEach(doc -> doc.setCreateTime(LocalDateTime.now()));
        documentService.saveAll(documents);
        return ResponseEntity.ok("批量创建成功，共创建 " + documents.size() + " 个文档");
    }

    /**
     * 根据ID获取文档
     */
    @GetMapping("/{id}")
    public ResponseEntity<Document> getDocument(@PathVariable("id") String id) {
        Optional<Document> document = documentService.findById(id);
        return document.map(ResponseEntity::ok)
                .orElse(ResponseEntity.notFound().build());
    }

    /**
     * 分页获取所有文档
     */
    @GetMapping
    public ResponseEntity<Page<Document>> getAllDocuments(
            @RequestParam(name = "page",defaultValue = "0") int page,
            @RequestParam(name = "size", defaultValue = "10") int size,
            @RequestParam(name = "sortBy", defaultValue = "createTime") String sortBy,
            @RequestParam(name = "sortDir", defaultValue = "desc") String sortDir) {
        
        Sort.Direction direction = sortDir.equalsIgnoreCase("desc") 
            ? Sort.Direction.DESC : Sort.Direction.ASC;
        Pageable pageable = PageRequest.of(page, size, Sort.by(direction, sortBy));
        
        Page<Document> documents = documentService.findAll(pageable);
        return ResponseEntity.ok(documents);
    }

    /**
     * 更新文档
     */
    @PutMapping("/{id}")
    public ResponseEntity<Document> updateDocument(@PathVariable String id, @RequestBody Document document) {
        Optional<Document> existing = documentService.findById(id);
        if (existing.isEmpty()) {
            return ResponseEntity.notFound().build();
        }
        
        document.setId(id);
        document.setCreateTime(existing.get().getCreateTime());
        Document updated = documentService.update(document);
        return ResponseEntity.ok(updated);
    }

    /**
     * 删除文档
     */
    @DeleteMapping("/{id}")
    public ResponseEntity<Void> deleteDocument(@PathVariable String id) {
        if (!documentService.existsById(id)) {
            return ResponseEntity.notFound().build();
        }
        documentService.deleteById(id);
        return ResponseEntity.ok().build();
    }

    /**
     * 删除所有文档
     */
    @DeleteMapping
    public ResponseEntity<String> deleteAllDocuments() {
        documentService.deleteAll();
        return ResponseEntity.ok("所有文档已删除");
    }

    /**
     * 根据标题搜索
     */
    @GetMapping("/search/title/{title}")
    public ResponseEntity<List<Document>> searchByTitle(@PathVariable String title) {
        List<Document> documents = documentService.findByTitle(title);
        return ResponseEntity.ok(documents);
    }

    /**
     * 根据作者搜索
     */
    @GetMapping("/search/author/{author}")
    public ResponseEntity<List<Document>> searchByAuthor(@PathVariable String author) {
        List<Document> documents = documentService.findByAuthor(author);
        return ResponseEntity.ok(documents);
    }

    /**
     * 根据标签搜索
     */
    @GetMapping("/search/tags")
    public ResponseEntity<List<Document>> searchByTags(@RequestParam List<String> tags) {
        List<Document> documents = documentService.findByTags(tags);
        return ResponseEntity.ok(documents);
    }

    /**
     * 全文搜索
     */
    @GetMapping("/search")
    public ResponseEntity<Page<Document>> search(
            @RequestParam String keyword,
            @RequestParam(defaultValue = "0") int page,
            @RequestParam(defaultValue = "10") int size) {
        
        Pageable pageable = PageRequest.of(page, size);
        Page<Document> documents = documentService.search(keyword, pageable);
        return ResponseEntity.ok(documents);
    }

    /**
     * 多字段搜索
     */
    @GetMapping("/search/multi")
    public ResponseEntity<Page<Document>> multiFieldSearch(
            @RequestParam String keyword,
            @RequestParam(defaultValue = "0") int page,
            @RequestParam(defaultValue = "10") int size) {
        
        Pageable pageable = PageRequest.of(page, size);
        Page<Document> documents = documentService.multiFieldSearch(keyword, pageable);
        return ResponseEntity.ok(documents);
    }

    /**
     * 高级搜索
     */
    @GetMapping("/search/advanced")
    public ResponseEntity<List<Document>> advancedSearch(@RequestParam String keyword) {
        List<Document> documents = documentService.advancedSearch(keyword);
        return ResponseEntity.ok(documents);
    }

    /**
     * 根据状态分页查询
     */
    @GetMapping("/status/{status}")
    public ResponseEntity<Page<Document>> getDocumentsByStatus(
            @PathVariable Integer status,
            @RequestParam(defaultValue = "0") int page,
            @RequestParam(defaultValue = "10") int size) {
        
        Pageable pageable = PageRequest.of(page, size, Sort.by("createTime").descending());
        Page<Document> documents = documentService.findByStatus(status, pageable);
        return ResponseEntity.ok(documents);
    }

    /**
     * 统计文档总数
     */
    @GetMapping("/count")
    public ResponseEntity<Long> countDocuments() {
        long count = documentService.count();
        return ResponseEntity.ok(count);
    }

    /**
     * 按作者聚合统计
     */
    @GetMapping("/stats/authors")
    public ResponseEntity<String> getAuthorStats() {
        documentService.aggregateByAuthor();
        return ResponseEntity.ok("聚合统计已执行，请查看日志");
    }

    /**
     * 批量保存（高性能）
     */
    @PostMapping("/bulk")
    public ResponseEntity<String> bulkSave(@RequestBody List<Document> documents) {
        documents.forEach(doc -> doc.setCreateTime(LocalDateTime.now()));
        documentService.bulkSave(documents);
        return ResponseEntity.ok("批量保存成功，共处理 " + documents.size() + " 个文档");
    }
}